package com.example.exception;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.example.common.Result;
import org.apache.catalina.connector.ClientAbortException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@ControllerAdvice(basePackages="com.example.controller")
public class GlobalExceptionHandler {

    private static final Log log = LogFactory.get();


    //统一异常处理@ExceptionHandler,主要用于Exception
    @ExceptionHandler(Exception.class)
    @ResponseBody//返回json串
    public Result error(HttpServletRequest request, HttpServletResponse response, Exception e){
        // 1. 检查是否是客户端断开连接异常
        if (e instanceof ClientAbortException) {
            log.debug("客户端断开连接: {}", e.getMessage());
            // 如果响应已经提交，直接返回null
            if (response.isCommitted()) {
                log.debug("响应已提交，跳过错误处理");
                return null;
            }
            // 返回特定错误信息
            return Result.error(String.valueOf(HttpStatus.BAD_REQUEST.value()), "客户端中断了连接");
        }

        // 2. 检查响应是否已经提交
        if (response.isCommitted()) {
            log.debug("响应已提交，跳过错误处理");
            return null;
        }
        log.error("异常信息：",e);
        return Result.error();
    }

    @ExceptionHandler(CustomException.class)
    @ResponseBody//返回json串
    public Result customError(HttpServletRequest request, CustomException e){
        return Result.error(e.getCode(), e.getMsg());
    }
}
